
#include <vector>

#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

#include "bocat/common/base64.hpp"

#include "oplogiter.hpp"

namespace	fekcab	{

OpLogIterator::OpLogIterator( const char* filename, const char* key_encode, const char* value_encode )
		:	_ifs( filename ),
			_key_encode( key_encode ),
			_value_encode( value_encode ),
			_key_encode_base64_b( false ),
			_value_encode_base64_b( false )
{
	if ( 0 == strcmp("base64", key_encode) ) {
		_key_encode_base64_b = true;
	}
	if ( 0 == strcmp("base64", value_encode) ) {
		_value_encode_base64_b = true;
	}

}

OpLogIterator::~OpLogIterator()
{
	if ( _ifs.is_open() ) {
		_ifs.close();
	}
}


///////////////////////////////////////////////////////////////////////
//


int	
OpLogIterator::next( Timestamp& ts, std::string& op, std::string& kpin, std::string& key, std::string& data )
{
	if ( !_ifs ) {
		return	0;
	}
	if ( !_ifs.is_open() ) {
		return	0;
	}
	if ( _ifs.eof() ) {
		return	0;
	}

	while ( !_ifs.eof() ) {
		std::string line;
		std::getline( _ifs, line );

		std::vector< std::string >  fields;
		boost::split(fields, line, boost::is_any_of("\t"));
		if ( fields.size() != 6 ) { 
			continue;
		}   

		// tv_sec \t tv_usec \t op \t kpin_b64 \t key_stored \t dat_stored \n
		const std::string&	tv_sec_s = fields[0];
		const std::string&	tv_usec_s = fields[1];

		struct	timeval	tv;
		tv.tv_sec = boost::lexical_cast< time_t >( tv_sec_s.c_str() );
		tv.tv_usec = boost::lexical_cast< suseconds_t >( tv_usec_s.c_str() );
		ts = Timestamp( tv );

		op = fields[2];
		kpin = bocat::common::base64_decode< std::string >( fields[ 3 ] );

		std::string& key_stored = fields[ 4 ];
		if ( _key_encode_base64_b ) {
			key = bocat::common::base64_decode< std::string >( key_stored );
		}
		else {
			key = key_stored;
		}
		std::string& data_stored = fields[ 5 ];
		if ( _value_encode_base64_b ) {
			data = bocat::common::base64_decode< std::string >( data_stored );
		}
		else {
			data = data_stored;
		}

		return	1;
	}

    return  0;  
}


}	//// namespace fekcab


